<template>
  <div class="relative px-22px py-22px bg-mask-5 h-full">
    <div class="absolute top-24px right-24px flex items-center cursor-pointer" @click="batchDelete">
      <img :src="orderUserDel" alt="" />
      <span class="color-white-opacity-6 text-14px ml-8px font-light">订单回收站</span>
    </div>
    <ul class="flex">
      <li
        v-for="tab in tabs"
        :key="tab.value"
        class="text-16px mr-34px cursor-pointer leading-23px"
        :class="{
          'color-sup font-medium': tab.value === active,
          'color-white-opacity-6': tab.value !== active
        }"
        @click="changeOrder(tab.value)"
      >
        {{ tab.label }}
      </li>
    </ul>
    <ul class="flex items-center h-55px text-white text-14px bg-mask-3 mt-10px">
      <li class="ml-24px w-400px">订单详情</li>
      <li class="text-center w-120px">单价</li>
      <li class="text-center w-120px">数量</li>
      <li class="text-center w-120px">总价</li>
      <li class="text-center flex-1">操作</li>
    </ul>
    <div
      v-for="(item, musterOrderId, index) in items"
      :key="musterOrderId"
      class="mt-22px border-user-order"
    >
      <div class="flex bg-mask-3 items-center pl-24px text-white h-55px text-14px">
        <n-checkbox v-model:checked="checked[index]" />
        <div class="ml-8px font-bold">{{ item[0]?.create_at }}</div>
        <div class="ml-14px">订单号：{{ musterOrderId }}</div>
        <div v-if="item[0]?.timeout" class="flex-1 text-right color-sup pr-14px">
          等待付款<n-countdown :duration="item[0]?.timeout" />
        </div>
      </div>
      <div v-for="order in item" :key="order.id">
        <div class="flex items-center h-121px">
          <div class="w-72px h-72px ml-24px mr-12px">
            <img
              :src="order.is_combo == 1 ? JSON.parse(order.imgs || '[]')?.[0]?.url : order.url"
              class="w-full h-full"
              alt=""
            />
          </div>
          <div class="w-316px">
            <div class="text-white leading-20px text-14px font-light">{{ order.name }}</div>
            <div class="color-white-opacity-6 text-12px leading-17px font-light mt-11px">
              <n-ellipsis style="max-width: 316px">
                {{ order.is_combo == 1 ? order.total : order.number }}份、{{
                  order.is_combo == 1
                    ? JSON.parse(order.skus || '[]').reduce((prev, sku, index) => {
                        return (prev +=
                          (index === 0 ? '' : ' | ') +
                          sku.name +
                          (JSON.parse(sku.combination || '[]')?.length
                            ? '(' +
                              JSON.parse(sku.combination || '[]')
                                ?.map((combination) => combination.value)
                                .join(',') +
                              ')'
                            : ''))
                      }, '')
                    : order.category
                }}
              </n-ellipsis>
            </div>
          </div>
          <div class="text-center w-120px text-white text-18px font-light">￥{{ order.price }}</div>
          <div class="text-center w-120px text-white text-14px">
            x{{ order.is_combo == 1 ? order.total : order.number }}
          </div>
          <div class="text-center w-120px text-18px color-sup font-medium">
            ￥{{ order.is_combo == 1 ? order.total * order.price : order.total }}
          </div>
          <!-- <div
            v-if="order.status == 2"
            class="flex-1 text-center flex flex-col items-center justify-center"
          >
            <div class="font-light text-white text-14px mt-12px cursor-pointer">待收货</div>
          </div> -->
          <div v-if="order.status == 8" class="flex-1 text-center flex flex-col items-center">
            <div class="text-white text-14px cursor-pointer" @click="buyAgain(order)">再次购买</div>
          </div>
        </div>
      </div>
      <div
        v-if="item[0]?.status == 2"
        class="flex-1 text-center flex items-center justify-end pb-14px pr-14px"
      >
        <div class="font-light text-white text-14px mt-12px cursor-pointer">待收货</div>
      </div>
      <div
        v-if="item[0]?.status == 1"
        class="flex-1 text-center flex items-center justify-end pb-14px pr-14px"
      >
        <div
          class="text-black text-14px cursor-pointer mr-14px w-76px h-28px rounded-24px bg-white leading-28px text-center"
          @click="cancelOrder(musterOrderId)"
        >
          取消订单
        </div>
        <div
          class="w-76px h-28px rounded-24px bg-sup color-word text-14px text-center leading-28px font-medium cursor-pointer"
          @click="gopay(musterOrderId)"
        >
          立即付款
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import dayjs from 'dayjs'
import orderUserDel from '@renderer/assets/userOrderDelete.svg'
import useHttp from '@renderer/utils/http'
import { useRoute, useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
const items = ref<any>({})
const checked = ref<boolean[]>([])
const tabs = [
  {
    label: '全部订单',
    value: 0
  },
  {
    label: '待付款',
    value: 1
  },
  {
    label: '待收货',
    value: 2
  },
  {
    label: '已完成',
    value: 8
  }
]
const route = useRoute()
const active = ref<any>(route.query.active ? Number(route.query.active) : 0)
const router = useRouter()
const message = useMessage()

const changeOrder = (index) => {
  active.value = index
  loadData(index)
}
onMounted(() => {
  loadData(active.value)
})
const gopay = (musterOrderId) => {
  router.replace({ name: 'Pay', query: { musterOrderId } })
}
const cancelOrder = async (musterOrderId) => {
  const { data: res } = await useHttp('/order/c/delete')
    .post({
      musterOrderId
    })
    .json()
  if (res.value.code === 200) {
    loadData(active.value)
  }
}
const loadData = async (status) => {
  const { data: res } = await useHttp('/order/user/c/list').get().json()
  const orders: any = {}
  if (res.value.code === 200) {
    Object.keys(res.value.data).forEach((musterOrderId) => {
      const os = res.value.data[musterOrderId]
      const orderStatus = os[0]?.status
      if (!status || orderStatus === status) {
        os.forEach((order) => {
          if (Number(order.is_combo) === 1) {
            order.create_at = dayjs(order.create_at).format('YYYY-MM-DD')
            return order
          }
          order.create_at = dayjs(order.create_at).format('YYYY-MM-DD')
          const skus = JSON.parse(order.skus)
          order.number = skus?.[0]?.number
          order.price = skus?.[0].price
          order.total = Number(order.number) * Number(order.price)
          order.url = skus?.[0]?.url
          order.name = skus?.[0]?.name
          const combination = skus?.[0].combination
          order.checked = false
          if (combination) {
            order.category = JSON.parse(combination).reduce((prev, combine, index, _) => {
              prev += combine.value + (index !== _.length - 1 ? '、' : '')
              return prev
            }, '')
          }
          return order
        })
        orders[musterOrderId] = os
      }
    })
  }
  console.log(orders)
  items.value = orders
}
// 批量删除订单
const batchDelete = async () => {
  const musterOrderIds: any = []
  // 获取选中的订单
  Object.keys(items.value).forEach((musterOrderId, index) => {
    if (checked.value[index]) {
      musterOrderIds.push(musterOrderId)
    }
  })
  const { data: res } = await useHttp('/order/c/batchDelete').post({ musterOrderIds }).json()
  if (res.value.code === 200) {
    message.info('回收成功')
    checked.value = []
    loadData(active.value)
  } else {
    message.error(res.value.message)
  }
}
// 再次购买
const buyAgain = (item) => {
  const spuId = JSON.parse(item.skus || '[]')?.[0].spu_id
  if (spuId) {
    router.replace({ name: 'Detail', params: { id: spuId } })
  }
}
</script>

<style scoped>
::v-deep(.n-checkbox-box) {
  --n-color-checked: #4979ff;
}
::v-deep(.n-checkbox-box__border) {
  --n-border-checked: none;
  --n-border-focus: none;
  --n-box-shadow-focus: 0 0 0 2px rgba(73, 121, 255, 0.3);
}
</style>
